package main.java.com.lee.juc;

import java.lang.management.ManagementFactory;
import java.lang.management.ThreadInfo;
import java.lang.management.ThreadMXBean;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Description TODO
 * @Author winston
 * @DateTime 2022/2/11
 */
public class DeadLockMonitorInterruptDemo {

    public static void main(String[] args) throws InterruptedException {
        ReentrantLock lock1 = new ReentrantLock();
        ReentrantLock lock2 = new ReentrantLock();

        Thread t1 = new Thread("t1") {
            @Override
            public void run() {
                try {
                    lockDemo(lock1, lock2);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        };

        Thread t2 = new Thread("t2") {
            @Override
            public void run() {
                try {
                    lockDemo(lock2, lock1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        };

        t1.start();
        t2.start();
        System.out.println("五秒后开始执行死锁检测");
        Thread.sleep(5000);
        ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
        long[] deadlockedThreads = threadMXBean.findDeadlockedThreads();
        if (deadlockedThreads.length > 0) {
            for (long deadlockedThread : deadlockedThreads) {
                ThreadInfo threadInfo = threadMXBean.getThreadInfo(deadlockedThread);
                System.out.println(threadInfo.toString());
            }
            t1.interrupt();
        }

        t1.join();
        t2.join();
    }

    private static void lockDemo(Lock lock1, Lock lock2) throws InterruptedException {
        lock1.lockInterruptibly();
        try {
            System.out.println("第一步加锁: 线程: " + Thread.currentThread().getName() + "加锁: " + lock1.toString() + "成功");
            lock2.lockInterruptibly();
            try {
                System.out.println("第二步加锁: 线程: " + Thread.currentThread().getName() + "加锁: " + lock2.toString() + "成功");
            }finally {
                lock2.unlock();
            }
        }finally {
            lock1.unlock();
        }
    }
}
